<template>
  <div class="attendance-container">
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/zuzhi/checkAttendance' }"
        >考勤情况</el-breadcrumb-item
      >
      <el-breadcrumb-item
        :to="{
          path: '/zuzhi/organizationList/myOrganizationList1',
          query: {
            oid: this.oid,
            fatherName: this.fatherName,
          },
        }"
        >我的组织详情</el-breadcrumb-item
      >
      <el-breadcrumb-item>课程考勤统计</el-breadcrumb-item>
      <!-- <el-breadcrumb-item>{{ fatherName }}</el-breadcrumb-item> -->
    </el-breadcrumb>

    <el-card class="header-card">
        <div style="font-size: 30px;font-weight: bold;" class="course-title">{{ childName }}</div>
        <!-- <div class="course-subtitle">课程考勤统计（学期汇总）</div> -->
    </el-card>

    <el-card class="attendance-card">
      <el-row :gutter="20">
        <el-col :span="16">
          <div class="chart-container">
            <div ref="stackedBarChart" style="width: 100%; height: 500px"></div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="right-panel">
            <div class="attendance-rate">
              <el-progress
                type="dashboard"
                :percentage="averageAttendanceRate"
                :color="colors"
                :width="220"
                :stroke-width="15"
              >
              </el-progress>
                <div class="rate-text">
                <div class="rate-title">平均到课率</div>
                <div
                  v-if="averageAttendanceRate > 80"
                  class="rate-value good"
                >
                  {{ averageAttendanceRate }}% <span class="rate-label"></span>
                </div>
                <div
                  v-else-if="averageAttendanceRate >= 60"
                  class="rate-value fair"
                >
                  {{ averageAttendanceRate }}% <span class="rate-label"></span>
                </div>
                <div v-else class="rate-value poor">
                  {{ averageAttendanceRate }}% <span class="rate-label"></span>
                </div>
                </div>
            </div>
            <!-- <div class="pie-chart-container">
                <div ref="pieChart" style="width: 100%; height: 300px;"></div>
              </div> -->
            <el-button
              type="primary"
              size="medium"
              @click="viewAttendanceActivities"
              style="margin-top: 25px; align-self: center"
            >
              查看签到活动
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'CourseAttendance',
  data() {
    return {
      ccid: '',
      oid: '',
      fatherName: '',
      childName: '',
      activities: [], // 存储所有签到活动数据
      averageAttendanceRate: 0, // 平均到课率
      colors: [
        { color: '#ea5851', percentage: 60 },
        { color: '#daa44f', percentage: 75 },
        { color: '#4c9df6', percentage: 90 },
        { color: '#5fcb71', percentage: 100 }
      ],
      ATTENDANCE_STATUS: {
        NORMAL: { code: 'normal', label: '按时签到', color: '#7bed9f' },
        LEAVE: { code: 'leave', label: '请假', color: '#70a1ff' },
        LATE: { code: 'late', label: '迟到', color: '#ffbb27' },
        ABSENT: { code: 'absent', label: '旷课', color: '#FF9496' },
        OTHER: { code: 'other', label: '其他', color: '#a4b0be' },
      },
      attendanceStats: {
        'normal': 0,
        'leave': 0,
        'late': 0,
        'absent': 0,
        'other': 0
      }
    }
  },
  
  created() {
    this.oid = this.$route.query.oid
    this.fatherName = this.$route.query.fatherName
    this.ccid = this.$route.query.ccid
    this.childName = this.$route.query.childName
    this.fetchAttendanceData()
  },
  mounted() {
    this.drawStackedBarChart()
    this.drawPieChart()
  },
  methods: {
    async fetchAttendanceData() {
      try {
        // 获取课程所有签到活动数据
        const { data: res } = await this.$http.get(
          '/cou/getCourseAttendanceStats',
          {
            params: { ccid: this.ccid },
          }
        )

        if (res.code === 200) {
          this.activities = res.data.activities
          this.calculateAverageStats()
          this.drawStackedBarChart()
          this.drawPieChart()
        }
      } catch (error) {
        console.error('获取考勤数据失败:', error)
      }
    },

    calculateAverageStats() {
      let totalRate = 0
      let activityCount = 0

      // 计算各项统计指标的平均值
      this.activities.forEach((activity) => {
        totalRate += activity.attendanceRate
        activityCount++

        // 累加各项考勤状态
        this.attendanceStats[`normal`] += activity.stats['normal'] || 0
        this.attendanceStats['leave'] += activity.stats['leave'] || 0
        this.attendanceStats['late'] += activity.stats['late'] || 0
        this.attendanceStats['absent'] += activity.stats['absent'] || 0
        this.attendanceStats['other'] += activity.stats['other'] || 0
      })

      // 计算平均到课率
      this.averageAttendanceRate =
        activityCount > 0
          ? parseFloat((totalRate / activityCount).toFixed(2))
          : 0
    },

   
    drawStackedBarChart() {
      const chart = echarts.init(this.$refs.stackedBarChart)

      // 准备x轴数据（活动名称）
      const activityNames = this.activities.map((act) => act.name)

      // 准备系列数据 - 使用统一的状态映射
      const series = Object.values(this.ATTENDANCE_STATUS).map((status) => ({
        name: status.label, // 使用中文标签
        type: 'bar',
        stack: 'total',
        data: this.activities.map((act) => act.stats[status.code] || 0),
        itemStyle: { color: status.color }, // 直接使用映射中的颜色
      }))

      const option = {
        title: {
          text: '课程考勤统计',
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
          formatter: function (params) {
            let result = params[0].name + '<br/>'
            let total = 0
            params.forEach((param) => {
              result += `${param.seriesName}: ${param.value}<br/>`
              total += param.value
            })
            result += `<b>总人数: ${total}</b>`
            return result
          },
        },
        legend: {
          // 使用中文标签
          data: series.map((item) => item.name),
          top: 30,
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: activityNames,
          axisLabel: {
            interval: 0,
            rotate: 30,
          },
        },
        yAxis: {
          type: 'value',
          name: '签到人数统计',
          nameLocation: 'middle',
          nameGap: 25,
        },
        series: series,
      }

      chart.setOption(option)
      window.addEventListener('resize', () => chart.resize())
    },
    drawPieChart() {
      const chart = echarts.init(this.$refs.pieChart)

      // 过滤掉值为0的项
      const pieData = Object.entries(this.attendanceStats)
        .filter(([_, value]) => value > 0)
        .map(([name, value]) => ({
          name,
          value,
          itemStyle: { color: this.getStatusColor(name) },
        }))

      const option = {
        title: {
          text: '考勤状态分布',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: pieData.map((item) => item.name),
        },
        series: [
          {
            name: '考勤状态',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: pieData,
          },
        ],
      }

      chart.setOption(option)
      window.addEventListener('resize', () => chart.resize())
    },

    // getStatusColor(status) {
    //   const colors = {
    //     //   'normal': '#5fcb71',
    //     //   'leave': '#4c9df6',
    //     //   'late': '#daa44f',
    //     //   'absent': '#ea5851',
    //     //   'other': '#9d9d9d'
    //     normal: '#7bed9f', //'#7ae679',
    //     leave: '#70a1ff', //'#50e1de',
    //     late: '#ffbb27',
    //     absent: '#ef2a57',
    //     other: '#a4b0be',
    //   }
    //   return colors[status] || '#9d9d9d'
    // },

      viewAttendanceActivities() {
        // 跳转到课程签到活动页面
        this.$router.push({
          path: '/zuzhi/courseHistory/courseHistory1',
          query: {
            oid: this.oid,
            fatherName: this.fatherName,
            ccid: this.ccid,
            curriculumName: this.childName
          }
        });
      },
  
    back() {
      this.$router.go(-1)
    },
  },
}
</script>

<style lang="scss" scoped>
.attendance-container {
  padding: 20px;

  .breadcrumb {
    margin-bottom: 20px;
  }

  .header-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 #0000001a;
    margin-bottom: 10px;

      .course-title {
        font-size: 30px;
        font-weight: bold;
        color: #333;
        margin-top: 2px;
        margin-bottom: 2px;
        text-align: center;
      }

      //   .course-subtitle {
      //     font-size: 16px;
      //     color: #666;
      //   }
    
  }

  .attendance-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .chart-container {
      background: #fff;
      border-radius: 6px;
      padding: 15px;
      height: auto;
      margin-left: 5px;
    }

    .right-panel {
      display: flex;
      flex-direction: column;
      height: 550px;

      .attendance-rate {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: auto;
        // background: #f9f9f9;
        // border-radius: 8px;
        margin-top: 25%;

        .rate-text {
          text-align: center;
          margin-top: 20px;

          .rate-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
          }

          .rate-value {
            font-size: 24px;
            font-weight: bold;

        //    &.excellent {
          //    color: #5fcb71;
            //}
            &.good {
              color: #4c9df6;   //>80
            }
            &.fair {
              color: #daa44f;    // 60-80
            }
            &.poor {
              color: #ea5851;     //<60
            }

            .rate-label {
              font-size: 16px;
              font-weight: normal;
            }
          }
        }
      }

      // .pie-chart-container {
      //   flex: 1;
      //   background: #fff;
      //   border-radius: 8px;
      //   padding: 15px;
      // }
    }
  }
}
</style>
